package com.sjyl.kaoshitong.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.artifex.mupdfdemo.MuPDFActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.sjyl.kaoshitong.R;
import com.sjyl.kaoshitong.adapter.MyDocumentFileRecyclerViewAdapter;
import com.sjyl.kaoshitong.beans.ApiResponse;
import com.sjyl.kaoshitong.beans.DocumentItem;
import com.sjyl.kaoshitong.beans.Recontent;
import com.sjyl.kaoshitong.util.APIUtils;
import com.sjyl.kaoshitong.util.KeyGen;
import com.sjyl.kaoshitong.util.NetworkUtil;
import com.sjyl.kaoshitong.util.OKHttpUtil;
import com.sjyl.kaoshitong.util.PreferencesKeyUtil;
import com.sjyl.kaoshitong.util.ToastUtil;
import com.sjyl.kaoshitong.util.Utility;
import com.sjyl.kaoshitong.witget.MoreContextMenu;
import com.sjyl.kaoshitong.witget.MoreContextMenuManager;
import com.squareup.okhttp.CacheControl;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import tr.xip.errorview.ErrorView;

/**
 * Created by ChangerLow on 15/6/12.
 * Email: changerlow@qq.com
 */
public class MyDocumentFileListFragment extends Fragment implements MyDocumentFileRecyclerViewAdapter.MyDocumentFileViewHolder.MyOnItemClickListener, MoreContextMenu.OnMoreContextMenuItemClickListener {
    private static final String TAG = "MyDocumentFileListFragment";
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private MyDocumentFileRecyclerViewAdapter recyclerViewAdapter;
    private List<DocumentItem> dataList;
    private LinearLayout refreshView;
    private ErrorView errorView;
    private LinearLayout emptyView;
    private OkHttpClient okHttpClient;
    private Gson gson = new Gson();
    private String pid;
    private int currentPage = 1;
    private KeyGen keyGen;


    public static MyDocumentFileListFragment newInstance(String pid, String title) {
        MyDocumentFileListFragment fragment = new MyDocumentFileListFragment();
        Bundle bundle = new Bundle();
        bundle.putString("pid", pid);
        bundle.putString("title", title);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Hawk.init(getActivity());
        Bundle bundle = getArguments();
        pid = bundle.getString("pid");
        Logger.d(TAG, "document file list pid is " + pid);
        keyGen = KeyGen.create(Utility.accessKey, Utility.secretKey);
        //db = Connector.getDatabase();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_document_file_list_layout, container, false);
        swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setColorSchemeResources(R.color.color_primary, R.color.color_primary_dark);
        refreshView = (LinearLayout) rootView.findViewById(R.id.refresh_layout);
        errorView = (ErrorView) rootView.findViewById(R.id.error_view);
        emptyView = (LinearLayout) rootView.findViewById(R.id.emptyview);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview);
        dataList = new ArrayList<>();
        layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerViewAdapter = new MyDocumentFileRecyclerViewAdapter(dataList);
        recyclerView.setAdapter(recyclerViewAdapter);
        recyclerViewAdapter.setOnItemClickListener(this);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                MoreContextMenuManager.getInstance().onScrolled(recyclerView, dx, dy);
            }
        });
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                recyclerViewAdapter.notifyDataSetChanged();
//                swipeRefreshLayout.setRefreshing(false);
            }
        });
        okHttpClient = OKHttpUtil.getOkHttpClient(getActivity());
        return rootView;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        showProgress();
        getData(currentPage);
    }


    @Override
    public void OnItemClick(View view, int position) {

    }

    @Override
    public void onItemMoreClick(View view, int position) {
        MoreContextMenuManager.getInstance().toggleContextMenuFromView(view, position, this);
    }

    @Override
    public void onReportClick(int feedItem) {
        MoreContextMenuManager.getInstance().hideContextMenu();
    }

    @Override
    public void onOpenClick(int feedItem) {
        MoreContextMenuManager.getInstance().hideContextMenu();
        //check download record in db and target path,  if exist? check version, not exist? download it and update db;
        //if version is invalid, show toast and download a new version one, else open the file;
        new DownloadTask(feedItem).execute();


    }

    @Override
    public void onStarClick(int feedItem) {
        MoreContextMenuManager.getInstance().hideContextMenu();
    }

    @Override
    public void onRatingClick(int feedItem) {
        MoreContextMenuManager.getInstance().hideContextMenu();
    }

    @Override
    public void onCancelClick(int feedItem) {
        MoreContextMenuManager.getInstance().hideContextMenu();
    }


    //open a new activity and open the pdf file
    public void openFileHandler(String path) {
        Logger.d(TAG, "open pdf file!");

        String[] strArray = path.split("/");
        int length = strArray.length;
        String fileName = strArray[length - 1];
        Logger.d(TAG, "fileName is " + fileName);
        Intent intent = new Intent(getActivity(), MuPDFActivity.class);
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.parse(path);
        intent.setData(uri);
        startActivity(intent);
    }


    private void getData(int page) {
        RequestBody body = new FormEncodingBuilder().add("funName", "getDataList").add("userId", Hawk.get(PreferencesKeyUtil.KEY_USER_ID, "")).add("keyWord", Hawk.get(PreferencesKeyUtil.KEY_KEY_WORD, "")).add("catalogId", pid).add("funpage", String.valueOf(page)).build();
        Request request = new Request.Builder().url(APIUtils.BASE_URL).post(body).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            Handler handler = new Handler(getActivity().getMainLooper());

            @Override
            public void onFailure(Request request, IOException e) {
                showErrorview();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                String body = response.body().string();
                Logger.json(TAG, body);

                Type type = new TypeToken<ApiResponse<DocumentItem>>() {
                }.getType();
                final ApiResponse<DocumentItem> apiResponse = gson.fromJson(body, type);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (!apiResponse.getRecode().equals("2000")) {
                            ToastUtil.SnackerShow(getActivity(), getActivity().getString(R.string.get_data_error));
                        } else {
                            Recontent<DocumentItem> recontent = apiResponse.getRecontent();

                            if (apiResponse.getRecontent() == null) {
                                showEmptyView();
                                return;
                            }
                            List<DocumentItem> list = recontent.getRelist();
                            if (list.size() == 0) {
                                showEmptyView();
                                return;
                            }
                            Logger.d(TAG, "=========recode:" + " relist size:" + list.size());
                            dataList.addAll(list);
                            recyclerViewAdapter.notifyDataSetChanged();
                            showContent();
                        }
                    }
                });
            }
        });
    }


    //下载文件异步任务
    class DownloadTask extends AsyncTask<Void, Integer, Integer> {
        private ProgressDialog progressDialog;
        private String url = "";
        //private final String CHARSET_UTF8 = Utility.UTF_8.displayName();
        private String filePath;
        private String dataId;
        private String userId;
        private int position;
        private DocumentItem item;

        DownloadTask(int position) {
            this.position = position;
            userId = Hawk.get("user_id", "");
            item = dataList.get(position);
            url = keyGen.privateDownloadUrl(item.getData_src());
            filePath = Utility.getFilePath(userId, item.getData_name());
            dataId = item.getId();
            Logger.d(TAG, "dataid " + dataId + "  download url " + url);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMax(100);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setIndeterminate(false);
            progressDialog.setMessage(getString(R.string.request_data));
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        }

        @Override
        protected Integer doInBackground(Void... args) {
            // FileOutputStream output;
            if (!NetworkUtil.isWifiDataEnable(getActivity()) && !NetworkUtil.isMobileDataEnable(getActivity())) {
                return -1;
            }
            //request download from backend;
            RequestBody body = new FormEncodingBuilder().add("funName", "doAddDownHis").add("userId", Hawk.get(PreferencesKeyUtil.KEY_USER_ID, "")).add("keyWord", Hawk.get(PreferencesKeyUtil.KEY_KEY_WORD, "")).add("dataId", dataId).build();
            Request rdRequest = new Request.Builder().url(APIUtils.BASE_URL).post(body).build();
            try {
                Response rdResponse = okHttpClient.newCall(rdRequest).execute();
                String jsonStr = rdResponse.body().string();
                JSONObject object = new JSONObject(jsonStr);
                if(!object.getString("recode").equals("2000") ){
                    return -2;
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }


            //if download document request's reponse is success
            OutputStream output;
            //OkHttpClient client = OKHttpUtil.getOkHttpClient(getActivity());
            Request request = new Request.Builder().cacheControl(new CacheControl.Builder().noCache().build()).url(url).build();
            try {
                Response response = okHttpClient.newCall(request).execute();
                if (response.code() == 200) {
                    InputStream inputStream = null;
                    inputStream = response.body().byteStream();
                    File file = new File(filePath);
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    output = new FileOutputStream(file);
                    long fileSize = response.body().contentLength();
                    byte bytes[] = new byte[1024];
                    double count = 0;
                    int length = 0;
                    while ((length = inputStream.read(bytes)) != -1) {
                        output.write(bytes, 0, length);
                        count += length;
                        int percent = (int) (count / fileSize * 100);
                        Integer[] arg = {percent};
                        publishProgress(arg);
                    }
                    output.flush();
                    output.close();
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return -3;
            }
            return 0;
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            if (result == 0) {
                dataList.get(position).setDown_status("1");
                recyclerViewAdapter.notifyDataSetChanged();
                if (progressDialog.isShowing())
                    progressDialog.dismiss();
                openFileHandler(filePath);
            } else if (result == -1) {
                if (progressDialog.isShowing())
                    progressDialog.dismiss();
                ToastUtil.SnackerShow(getActivity(), getResources().getString(R.string.httpError));
            } else if(result == -2) {
                if(progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
                ToastUtil.SnackerShow(getActivity(), getResources().getString(R.string.not_enough_gold));
            }else {
                if (progressDialog.isShowing())
                    progressDialog.dismiss();
                ToastUtil.SnackerShow(getActivity(), getResources().getString(R.string.download_error));
            }

        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            if (values[0] >= 2) {
                progressDialog.setProgress(values[0]);
                progressDialog.setMessage(getString(R.string.data_downloading) + " " + values[0] + "%");
            }
        }
    }

    private void showProgress() {
        refreshView.setVisibility(View.VISIBLE);
        swipeRefreshLayout.setVisibility(View.GONE);
        errorView.setVisibility(View.GONE);
        emptyView.setVisibility(View.GONE);
    }

    private void showContent() {
        refreshView.setVisibility(View.GONE);
        swipeRefreshLayout.setVisibility(View.VISIBLE);
        errorView.setVisibility(View.GONE);
        emptyView.setVisibility(View.GONE);
    }

    private void showEmptyView() {
        refreshView.setVisibility(View.GONE);
        swipeRefreshLayout.setVisibility(View.GONE);
        errorView.setVisibility(View.GONE);
        emptyView.setVisibility(View.VISIBLE);
    }

    private void showErrorview() {
        refreshView.setVisibility(View.GONE);
        swipeRefreshLayout.setVisibility(View.GONE);
        errorView.setVisibility(View.VISIBLE);
        emptyView.setVisibility(View.GONE);

    }


}
